package com.corp.common.base.util;

import com.corp.common.base.constant.SystemConstant;
import com.corp.platform.common.converter.json.JSONBinder;
import com.corp.platform.common.response.RespResult;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HttpContextUtils {

    public static HttpServletRequest getHttpServletRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public static String getDomain() {
        HttpServletRequest request = getHttpServletRequest();
        StringBuffer url = request.getRequestURL();
        return url.delete(url.length() - request.getRequestURI().length(), url.length()).toString();
    }

    public static String getOrigin() {
        HttpServletRequest request = getHttpServletRequest();
        return request.getHeader("Origin");
    }

    public static String getContextPath() {
        HttpServletRequest request = getHttpServletRequest();
        return request.getContextPath();
    }

    public static void response(HttpServletResponse response, RespResult result) throws Exception {
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(SystemConstant.UTF_8);
        response.getWriter().write(JSONBinder.toJsonStr(result));
    }
}
